package util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

@WebFilter(filterName = "JWT_Filter",urlPatterns = ("/*"))
public class JWT_Filter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request_Servlet,
                         ServletResponse response_Servlet,
                         FilterChain chain)
            throws IOException, ServletException {
        System.out.println("JWT_Filter - begins");
        HttpServletRequest request = (HttpServletRequest) request_Servlet;
        HttpServletResponse response = (HttpServletResponse) response_Servlet;

        String path = request.getRequestURI();

        if (!path.contains("/login")){
            //设置响应字符编码为UTF-8
            response.setContentType("application/json;charset=UTF-8");
            //获取token令牌
            String token = request.getHeader("token");

            if (token != null) {
                //调用TokenHelper的verify方法对token进行验证，验证结果存在verify集合里
                Collection<String> verify = TokenHelper.verify(token, response);
                JSONObject message = new JSONObject();

                message.put("登录成功", verify.toString());
                response.getWriter().println("登录成功");
            }

            System.out.println("JWT_Filter - encoding ends");
        }
        chain.doFilter(request_Servlet,response_Servlet);

    }

    @Override
    public void destroy() {

    }
}
